<?php
	class Login{
		
		private $language;
		
    	public function __construct(){
			$this->language = explode("\n",file_get_contents("web3g/language/EN-login.txt"));
		}
		public function getAction($value){
			if(array_key_exists('login', $value)){
				return $this->CheckLogin($value);
			}
			if(array_key_exists('register', $value)){
				return $this->Register($value);
			}
			if(array_key_exists('changedetails', $value)){
				return $this->AccountDetails($value);
			}
		}
		private function Register($value){
			if(($value['email'] == $value['email2']) && ($value['password'] == $value['password2'])){
				$sql = "SELECT * FROM CostBiterUsers WHERE EMail = '".$value['email']."'";
				
				$result = DB::query($sql);
				
				if(mysql_num_rows($result) == 0){
					$sql = "INSERT INTO CostBiterUsers (EMail,Password) VALUES ('".$value['email']."','".$this->Encode($value['password'])."')";
					DB::query($sql);
					//user has been registered
					return $this->language[1];
				}else{
					//user is already registered
					return $this->language[0];
				}
			}else{
				//incorrect fields
				return $this->language[2];
			}
		}
		public function CheckStatus(){
			if(isset($_SESSION['user']) && isset($_SESSION['code'])){
				$sql = "SELECT * FROM CostBiterUsers WHERE EMail = '".$_SESSION['user']."'";
				$result = DB::query($sql);
				$fetch = DB::fetch($result);
				if(Login::Encode($fetch['EMail'].$fetch['Password']) == $_SESSION['code']){
					return true;
				}else{
					return false;
				}
			}
		}
		private function CheckLogin($value){
			$sql = "SELECT * FROM CostBiterUsers WHERE EMail = '".$value['email']."'";
			$result = DB::query($sql);
			$fetch = DB::fetch($result);
			if(mysql_num_rows($result) == 1){
				if($this->Encode($value['password']) == $fetch['Password']){
					//Login is correct
					$this->SetLogin($value['email'],$this->Encode($value['email'].$fetch['Password']));
					return $this->language[3];
				}else{
					//Login is incorrect
					return $this->language[4];
				}
			}else{
				return $this->language[4];
			}
		}
		private function SetLogin($user,$pass){
			$_SESSION['user']=$user;
			$_SESSION['code']=$pass;
		}
		private function Encode($value){
			return md5($value);
		}
		private function AccountDetails($value){
			$sql = "UPDATE CostBiterUsers SET ".
					"Firstname = '".$value['Firstname']."', ".
					"Surname = '".$value['Surname']."', ".
					"Address = '".$value['Address']."', ".
					"DeliveryName='".$value['DeliveryName']."', ".
					"DeliveryAddress='".$value['DeliveryAddress']."'";
			DB::query($sql);
		}
	}
?>